<?php

namespace App\Models;


use App\Service\Base\Model;
use Illuminate\Support\Facades\DB;

class UserFan extends Model
{

    // 用户管理
    protected $table = 'user_fan';

    // 缓存字段，用于搜索绑定的字段
    protected $cacheFields = ['id', 'uid', 'auth_id', 'auth_uid', 'status'];

    //  {"id":"自编号","uid":"访问用户编码","auth_id":"关注用户的认证ID","auth_uid":"关注用户的ID","status":"状态 1-是","ctime":"添加时间","mtime":"修改时间"}


    // array ( 'id' => '$this->getData("id", null, "trim")', 'uid' => '$this->getData("uid", null, "trim")', 'auth_id' => '$this->getData("auth_id", null, "trim")', 'auth_uid' => '$this->getData("auth_uid", null, "trim")', 'status' => '$this->getData("status", null, "trim")', 'ctime' => '$this->getData("ctime", null, "trim")', 'mtime' => '$this->getData("mtime", null, "trim")', )


    //$id = $this->getData("id", null, 'trim'); $uid = $this->getData("uid", null, 'trim'); $auth_id = $this->getData("auth_id", null, 'trim'); $auth_uid = $this->getData("auth_uid", null, 'trim'); $status = $this->getData("status", null, 'trim'); $ctime = $this->getData("ctime", null, 'trim'); $mtime = $this->getData("mtime", null, 'trim');

    // 关注操作
    public function onFollow($uid, $auth_id)
    {
        // 事务操作
        $model = new UserAuth();
        DB::beginTransaction();
        try{
            // 查询关注的认证用户
            $where = ['id' => $auth_id, 'verify' => 1];
            $info  = $model->where($where)->lockForUpdate()->first();
            if(empty($info)){
                throw new \Exception('你要关注的认证用户不存在或者被禁用！');
            }


            // 是否已经关注
            $isWhere = ['uid' => $uid, 'auth_id' => $auth_id];
            $isInfo  = $this->where($isWhere)->lockForUpdate()->first();

            // 数据操作
            if(empty($isInfo)){
                $status   = 1;
                $follData = ['uid' => $uid, 'auth_id' => $auth_id, 'status' => 1];
                $numbers  = ['follow_no' => DB::raw('follow_no + 1')];
                $this->fill($follData);
            } else{
                if($isInfo['status'] == 1){
                    $status   = 0;
                    $follData = ['status' => 0];
                    $numbers  = ['follow_no' => DB::raw('follow_no - 1')];
                } else{
                    $status   = 1;
                    $follData = ['status' => 1];
                    $numbers  = ['follow_no' => DB::raw('follow_no + 1')];
                }
                $isInfo->fill($follData);
            }

            // 关注
            if(empty($isInfo)){
                $result = $this->save();
            } else{
                $result = $isInfo->save();
            }

            // 更新关注用户的：关注人数
            $model->where('id', $auth_id)->update($numbers);

            // 提交事务
            DB::commit();
        } catch(\Exception $e){
            // 回滚事务
            DB::rollback();
            $error = $this->getError() ?: $e->getMessage();

            return $this->return_false($error, 5000);
        }

        // 缓存操作
        //$userDb->reSaveCache($uid, $numCache);
        $this->deleteCacheShow($follData, $isInfo);
        $model->deleteCacheShow(['id' => $auth_id]);

        return $status;
    }

    // 是否关注
    public function isFollow($uid, $auth_id)
    {
        if(empty($uid) || empty($auth_id)){
            return 0;
        }

        $where  = ['uid' => $uid, 'auth_id' => $auth_id];
        $isInfo = $this->isCache(true)->oneFind($where);

        // 数据操作
        $status = 0;
        if($isInfo && ($isInfo['status'] == 1)){
            $status = 1;
        }

        return $status;
    }


    // 获取用户的粉丝（关注我的人）
    public function getFans($where, $page = 1, $rows = 10, $order = "id DESC")
    {
        // 获取缓存
        $bang     = $this->bang;
        $is_cache = $this->is_cache || $bang;
        $args     = compact('where', 'page', 'rows', 'order');
        if($is_cache){
            $cacheName = $this->cacheKey('lists_getFans', $args);
            $result    = $this->cacheClass()->getCache($cacheName);
            // 检查是否已经绑定
            if(($result) && (!empty($result['list']))){
                $this->checkBangList($result['list'], $cacheName);
            }
        }
        if(empty($result)){
            // 查询
            $query = $this->where($where)->forPage($page, $rows);
            $count = $this->where($where)->count();
            if(is_array($order)){

            } else{
                $order = explode(" ", $order);
                $query = $query->orderby($order[0], $order[1]);
            }
            $lists = $query->get()->toArray();
        } else{
            $lists = $result['table'];
        }


        // 获取用户
        $users = [];
        if($lists){
            $userDb = new User();
            $uids   = array_column($lists, 'uid');
            $users  = $userDb->isCache(true)->getListInIds($uids);
            $users  = array_values($users);
        }

        $result = ['count' => $count, 'page' => $page, 'rows' => $rows, 'list' => $users, 'table' => $lists,];
        // 保存为缓存
        if($is_cache && $lists){
            $this->addCacheList($lists, $cacheName, $result, 'list');
            $userDb->addBangList($users, $cacheName);
        }

        return $result;
    }


    // 定义验证操作
    public function rules()
    {

        $add = [
        ];

        $edit = [
        ];

        $info = [
        ];


        $rule = [
            'uid'      => 'required',
            'auth_id'  => 'required',
            'auth_uid' => 'required',
            'status'   => 'in:0,1',
        ];


        $msg = [
            'id'       => '自编号',
            'uid'      => '访问用户编码',
            'auth_id'  => '关注用户的认证ID',
            'auth_uid' => '关注用户的ID',
            'status'   => '状态 1-是',
            'ctime'    => '添加时间',
            'mtime'    => '修改时间',
        ];

        return ['rule' => $rule, 'msg' => $msg, 'add' => $add];
    }
}
